#include "Texture.h"
#include "SOIL.h"

namespace glow
{
	using namespace std;
	
    /*@param String contenant l'adresse exacte de l'image source (.jpeg, .png...)*/
	Texture::Texture(string filename) : IResource(filename), _data(NULL), _idText(0)
    {
        load(filename);
    }

    /*Destructeur de la classe Texture*/
    Texture::~Texture()
    {
        if(_data)
			delete[] _data;
    }

	const Vector2i &Texture::getSize() const
	{
		return _size;
	}
	
    /*Accesseur de l'attribut m_colorTab : char *
    Renvoi le tableau de couleur de la texture
    */
    unsigned char *Texture::getData() const
    {
        return _data;
    }

    /*Accesseur de l'attribut m_identTexture : GLuint
    Renvoi l'identifiant de la texture
    */
    GLuint Texture::getGLID() const
    {
        return _idText;
    }

    void Texture::load(string filename)
    {
        int channels;
        _data = SOIL_load_image
        (
            filename.c_str(),
            &_size.x, &_size.y, &channels,
            SOIL_LOAD_AUTO
        );

		if(_data)
		{
			_idText = SOIL_create_OGL_texture
			(
				_data,
				_size.x, _size.y, channels,
				SOIL_CREATE_NEW_ID,
				SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y | SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT
			);

			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		}
		else
			cerr << "Error while loading Texture from " << filename << endl;
    }

}//namespace glow
